<template>
  <a-space class="mb-15">
    <div>
      <a-button @click="firstPage"> 首页 </a-button>
    </div>

    <div>
      <span>&nbsp;&nbsp; 10s 刷新一次数据：</span>
      <a-switch v-model:checked="autoRefresh" checked-children="开" un-checked-children="关" />
    </div>
  </a-space>

  <a-spin :spinning="loading">
    <a-steps progress-dot direction="vertical">
      <a-step v-for="item in dataSource" :key="item.id" status="process" :title="item.text" />
      <div v-if="showLoadingMore" :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }">
        <a-spin v-if="loadingMore" />
        <a-button v-else @click="onLoadMore"> 更多... </a-button>
      </div>
    </a-steps>
  </a-spin>
</template>
<script>
import { defineComponent, onBeforeUnmount, onMounted, reactive, toRefs, watch } from "vue";
import { get } from "@/services/request";
import tools from "@/services/tools";
import moment from "moment";
export default defineComponent({
  props: {
    formId: String,
  },
  setup(props) {
    const state = reactive({
      vm: props.formId,
      loading: true,
      loadingMore: false,
      showLoadingMore: true,
      table: {
        page: 1,
        size: 20,
      },
      dataSource: [],
      input: "1",
      timer: null,
      //自动刷新
      autoRefresh: window.localStorage.getItem("autoRefresh") == 1,
    });

    const methods = {
      getloginfo() {
        state.loading = true;
        get(`/JobLogger/${state.vm}/${state.table.page}/${state.table.size}`)
          .finally(() => {
            state.loading = false;
            state.loadingMore = false;
          })
          .then((res) => {
            if (res.data.length > 0) {
              if (state.table.page == 1) state.dataSource = res.data.concat(state.dataSource);
              else state.dataSource = state.dataSource.concat(res.data);
            } else {
              tools.message("未查询到数据");
              state.showLoadingMore = false;
            }
          });
      },
      onLoadMore() {
        state.loadingMore = true;
        state.table.page += 1;
        methods.getloginfo(state.table.page);
      },
      firstPage() {
        state.table.page = 1;
        state.dataSource = [];
        methods.getloginfo();
      },
      timeFormat(time) {
        return moment(time).format("YYYY-MM-DD HH:mm:ss");
      },
    };

    watch(
      () => state.autoRefresh,
      (value) => {
        window.localStorage.setItem("autoRefresh", value ? 1 : 0);
      }
    );

    onMounted(() => {
      state.autoRefresh = window.localStorage.getItem("autoRefresh") == 1;
      methods.getloginfo();
      state.timer = setInterval(() => {
        if (state.autoRefresh) {
          methods.getloginfo();
        }
      }, 5 * 1000);
    });

    //组件销毁时
    onBeforeUnmount(() => {
      if (state.timer) clearInterval(state.timer);
    });

    return {
      ...toRefs(state),
      ...methods,
    };
  },
});
</script>
